<script setup lang="ts">
import { getCurrentInstance, onBeforeMount, onUnmounted, Ref, ref } from "vue";
import { Subject, Subscription } from "rxjs";
import { useContextParams, handleMenusResource, menuSelect } from "@core";
import { IParam, IActionParam } from "@interface";
import { AppMenuItem } from "@components";
import { useRoute, useRouter } from "vue-router";
interface MenuProps{
  /**
   * @description 部件名称
   */
  name: string;

  /**
   * @description 传入上下文
   */
  contextProp: IParam;

  /**
   * @description 传入视图参数
   */
  viewParamsProp?: IParam;

  /**
   * @description 视图状态
   */
  viewState: Subject<IActionParam>;

  /**
   * @description 菜单方向
   */
  menuAlign: "LEFT" | "TOP" | "CENTER" | "TABEXP_LEFT" | "TABEXP_TOP" | "TABEXP_RIGHT" | "TABEXP_BOTTOM" | "NONE";

  /**
   * @description 默认视图
   */
  defaultView: string;
}
const props = withDefaults(defineProps<MenuProps>(), {
  menuAlign: "LEFT",
});
const { context, viewParams } = useContextParams(props);
let viewStateEvent: Subscription | undefined;
const menu = getCurrentInstance()?.vnode;
defineExpose({
  menu
})
/**
 * @description 菜单项集合
 */
const menus: Ref<IParam[]> = ref([
  {
    id: "1",
    title: "菜单项1",
    expanded: true,
    items: [
      {
        id: "3",
        title: "菜单项3",
      },
      {
        id: "4",
        title: "编辑视图",
        openDefault: true,
        funcTag: "1",
      },
    ]
  },
  {
    id: "2",
    title: "菜单项2",
  }
]);

const defaultOpens: Ref<string[]> = ref([]);
const defaultSelect: Ref<string[]>= ref([]);
const router = useRouter();
const route = useRoute();
/**
 * @description 应用功能集合
 */
const funcs: IParam[] = [{
  funcTag: "1",
}];

const modelParam = {
  funcs: funcs,
}

const runtimeParam = {
  menus: menus,
  context: context,
  defaultView: props.defaultView,
  authService: {},
  defaultOpens: defaultOpens,
  defaultSelect: defaultSelect,
  viewParams: viewParams,
  mode: props.menuAlign,
  router: router,
  route: route,
}
const onSelect = (item: any, key: any, selectedKeys: any) => {
  menuSelect(modelParam, runtimeParam);
}
onBeforeMount(() => {
  if (props.viewState) {
    viewStateEvent = props.viewState.subscribe(({ tag, action, data }: IActionParam) => {
      if (Object.is(tag, props.name)) {
        switch (action) {
          case 'load':
            handleMenusResource(modelParam, runtimeParam);
            break;
        }
      }
    });
  }
})
onUnmounted(() => {
  if (viewStateEvent) {
    viewStateEvent.unsubscribe();
  }
})
</script>

<template>
  <a-menu
    v-model:openKeys="defaultOpens"
    v-model:selectedKeys="defaultSelect"
    :mode="Object.is('LEFT', menuAlign) ? 'inline' : 'horizontal'"
    @select="onSelect">
    <AppMenuItem :items="menus" />
  </a-menu>
</template>

<style scoped>

</style>